package com.running.base.run.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * TODO
 *
 * @author luxun
 * @version 1.0
 * @date 2021/5/20 10:24 下午
 */
public class OssClientUtil {


    /**
     * oss文件上传
     * @param ossClient
     * @param fileInputStream
     * @param bucket
     * @param ossPath
     * @return
     */
    public static boolean storeFileToOss(OSSClient ossClient, InputStream fileInputStream, String bucket, String ossPath) {
        PutObjectResult putObjectResult = ossClient.putObject(bucket, ossPath, fileInputStream);
        if (null != putObjectResult && StringUtils.isNotBlank(putObjectResult.getRequestId())) {
            return true;
        } else {
            return false;
        }
    }

    public static void downOssFile(OSSClient ossClient, String ossPath, HttpServletResponse response) {
        String bucket = StringUtil.getBucket(ossPath);
        ossPath = StringUtil.removeOssPrefix(ossPath);
        try {
            StreamUtils.copy(ossClient.getObject(bucket, ossPath).getObjectContent(), response.getOutputStream());
        } catch (IOException e) {
            try {
                StreamUtils.copy(ossClient.getObject(bucket, ossPath).getObjectContent(), response.getOutputStream());
            } catch (IOException ioException) {
            }
        }
    }
}
